package com.leetcode;

/**
 * AddTwoNumber.. meiyou zuochulai ,can kao da an xiugai
 *
 * @author Lizhong
 * @date 2019/3/2
 */
public class AddTwoNumber {
    /**
     * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
     * Output: 7 -> 0 -> 8
     * Explanation: 342 + 465 = 807.
     * @param args
     */
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(2);
        ListNode listNode2 = new ListNode(4);
        ListNode listNode3 = new ListNode(3);
        listNode1.next = listNode2;
        listNode2.next = listNode3;

        ListNode listNode4 = new ListNode(5);
        ListNode listNode5 = new ListNode(6);
        ListNode listNode6 = new ListNode(4);
        listNode4.next = listNode5;
        listNode5.next = listNode6;

        ListNode listNode = Solution.addTwoNumbers(listNode1, listNode4);
        System.out.println("gg");


    }
}

/**
 * Definition for singly-linked list.*/
class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

class Solution {
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        int numb1 = 0;
        ListNode l0 = new ListNode(0), l = l0; // hexin
        boolean flag = false;
        for (int i = 0; !(l1 == null && l2 == null); i++) {
            if (l1 != null && l2 != null) {

                int m = l1.val + l2.val;
                if (flag == true) {
                    m++;
                }
                if (m < 10) {
                    l.next = new ListNode(m);
                    flag = false;
                } else {
                    l.next = new ListNode(m % 10);
                    flag = true;
                }
            } else if (l1 != null) {
                int m = l1.val;
                if (flag == true) {
                    m++;
                }
                if (m < 10) {
                    l.next = new ListNode(m);
                    flag = false;
                } else {
                    l.next = new ListNode(m % 10);
                    flag = true;
                }
            } else {
                int m = l2.val;
                if (flag == true) {
                    m++;
                }
                if (m < 10) {
                    l.next = new ListNode(m);
                    flag = false;
                } else {
                    l.next = new ListNode(m % 10);
                    flag = true;
                }
            }

            l = l.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;

        }
        if (flag) {
            l.next = new ListNode(1);  // rong yilou
        }
        return l0.next;
    }

}